//
//  RHEditInforViewController.m
//  RuiHeAppApp
//
//  Created by Jun on 2023/7/20.
//

#import "RHEditInforViewController.h"
#import "RHPublicEditViewController.h"
#import "RHEditInforCell.h"
#import "RHEditHeadCell.h"
#import "RHMyQRCodeVC.h"
#import "CDZQRScanViewController.h"
#import "RHNavigationController.h"
#import "NetworkConfig.h"
#import "RHMySuperUserInfoVC.h"

@interface RHEditInforViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) UIView *headerView;

@property (nonatomic ,strong) UIView *footerView;

@property (nonatomic, strong) UIImage *uploadImg;
//要修改的信息
@property (nonatomic, strong) NSMutableDictionary *editInfoDic;

@property (nonatomic ,strong) NSArray *titles;
@end

@implementation RHEditInforViewController
-(NSMutableDictionary *)editInfoDic
{
    if(!_editInfoDic){
        _editInfoDic = [[NSMutableDictionary alloc]init];
    }
    return _editInfoDic;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear: animated];
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"编辑个人信息".rh_localized];
    [self.view setBackgroundColor:CFTabViewBgColor];
    [self setupUI];
}

- (void)setupUI{
    
    self.titles = @[@"",@"昵称".rh_localized,@"电话".rh_localized,@"地区".rh_localized,@"地址".rh_localized,@"上级用户".rh_localized];
    //终端用户以上 展示二维码(隐藏掉)
//    BOOL isShowQRCode = [PrivateMange share].currentUser.hierarchyCode <= UserRoleTypeTerminalUser && [PrivateMange share].currentUser.hierarchyCode>UserRoleTypeBrandMerchants;
//    if(isShowQRCode){
//       self.titles = @[@"",@"昵称".rh_localized,@"电话".rh_localized,@"地区".rh_localized,@"地址".rh_localized,@"我的二维码".rh_localized,@"上级用户".rh_localized];
//    }
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHEditHeadCell class] forCellReuseIdentifier:@"RHEditHeadCell"];
    [_tableView registerClass:[RHEditInforCell class] forCellReuseIdentifier:@"RHEditInforCell"];
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    QMUIButton *sureBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [sureBtn setTitle:@"确定".rh_localized forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sureBtn setCornerRadius:8];
    [sureBtn setBackgroundColor:CMainColorGreen];
    [self.view addSubview:sureBtn];
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(20);
            make.right.mas_offset(-20);
            make.bottom.mas_offset(-kSafe_bottom-20);
            make.height.offset(kScaleW(45));
    }];
    [sureBtn addTarget:self action:@selector(uploadHeadImage) forControlEvents:UIControlEventTouchUpInside];
}

- (UIView *)footerView{
    if(!_footerView){
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,200)];
        [_footerView setBackgroundColor:UIColor.clearColor];
        
        UIView *view =  [[UIView alloc] initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH-30,200)];
        [view setBackgroundColor:UIColor.whiteColor];
        [view round:5 RectCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight];
        [_footerView addSubview:view];
    }
    return _footerView;
}

- (UIView *)headerView{
    if(!_headerView){
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,40)];
        [_headerView setBackgroundColor:UIColor.clearColor];
        
        UIView *view =  [[UIView alloc] initWithFrame:CGRectMake(15, 20, SCREEN_WIDTH-30,20)];
        [view setBackgroundColor:UIColor.whiteColor];
        [view roundBorder:8 width:1 color:kBorderColor RectCorners:QMUIViewBorderPositionLeft|QMUIViewBorderPositionTop|QMUIViewBorderPositionRight];
        [_headerView addSubview:view];
    }
    return _headerView;
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.titles.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
   return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.row == 0){
        RHEditHeadCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHEditHeadCell"];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        [cell setHeadVStr:[PrivateMange share].currentUser.avatar];
        [cell setTitleStr:@"个人头像".rh_localized];
        [cell setTopBorder];
        return cell;
    }else{
        RHEditInforCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHEditInforCell"];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
        NSString *title = self.titles[indexPath.row];
        [cell setTitleStr:title];
        if([title isEqualToString:@"昵称".rh_localized]){//昵称
            [cell setContentStr:[PrivateMange share].currentUser.nickName];
        }else if([title isEqualToString:@"电话".rh_localized]){//电话
            [cell setContentStr:[PrivateMange share].currentUser.phonenumber];
        }else if([title isEqualToString:@"地区".rh_localized]){//地区
            [cell setContentStr:[PrivateMange share].currentUser.serverArea];
            [cell hideArrowImage];
        }else if([title isEqualToString:@"地址".rh_localized]){//地址
            [cell setContentStr:[PrivateMange share].currentUser.address];
        }else if([title isEqualToString:@"上级用户".rh_localized]){//
            [cell setContentStr:ValidNullDataToString([PrivateMange share].currentUser.superAdminEmail,@"暂无".rh_localized)];
        }else if([title isEqualToString:@"我的二维码".rh_localized]){//我的二维码
            UIImageView *qrCodeImg = [[UIImageView alloc] init];
            [qrCodeImg setImage:[UIImage imageNamed:@"kwt_mine_qr_code"]];
            [cell.contentView addSubview:qrCodeImg];
            [qrCodeImg mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.height.offset(15);
                make.centerY.mas_offset(0);
                make.right.mas_offset(-55);
            }];
            
        }
        if (indexPath.row == self.titles.count - 1) {
            [cell setBottomBorder];
        }else{
            [cell setMiddleBorder];
        }
        return cell;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //是否展示二维码
    BOOL isShowQRCode = [PrivateMange share].currentUser.hierarchyCode <= UserRoleTypeTerminalUser && [PrivateMange share].currentUser.hierarchyCode>UserRoleTypeBrandMerchants;
    
    NSString *title = self.titles[indexPath.row];
    
    if([title isEqualToString:@"地区".rh_localized])return;//地区和上级电话不可编辑
    if(indexPath.row == 0){
        //编辑头像
        [self addPicAction];
    }else if([title isEqualToString:@"我的二维码".rh_localized]){
        
        //安装工人以上级别,展示自己的二维码,品牌商不展示
        if(isShowQRCode){
            [self.navigationController pushViewController:[RHMyQRCodeVC new] animated:YES];
        }else if([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeNormalUser){
            //普通用户,扫描二维码,绑定关系
            [self scanQRC];
        }
        
    }else if([title isEqualToString:@"上级用户".rh_localized]){
        RHMySuperUserInfoVC *superInfoVC = [[RHMySuperUserInfoVC alloc]init];
        [self.navigationController pushViewController:superInfoVC animated:YES];
    }else{
        //这里跟后台要传的参数 key 值一样
        NSArray *keys = @[@"avatar",@"nickName",@"phonenumber",@"",@"address",@""];
        NSString *phone = [PrivateMange share].currentUser.phonenumber;
        NSString *nickName = [PrivateMange share].currentUser.nickName;
        NSString *address = [PrivateMange share].currentUser.address;
       
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if ([cell isKindOfClass:[RHEditInforCell class]]) {
            RHEditInforCell *editCell = (RHEditInforCell*)cell;
            nickName = editCell.contentStr;
            address = editCell.contentStr;
            phone = editCell.contentStr;
        }
        NSArray *contents = @[@"",ValidNullData(nickName),ValidNullData(phone),@"",ValidNullData(address),@""];
        NSString *content = contents[indexPath.row];
        RHPublicEditViewController *vc = [[RHPublicEditViewController alloc] init];
        vc.title = self.titles[indexPath.row];
        vc.editInfoDic = self.editInfoDic;
        vc.key = keys[indexPath.row];
        vc.content = content;
        vc.idx = indexPath.row;
        kWeakSelf;
        vc.selectBlock = ^(NSInteger idx) {
            NSLog(@"===>要修改的信息:%@",weakSelf.editInfoDic);
            RHEditInforCell *cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:0]];
            [cell setContentStr:weakSelf.editInfoDic[keys[idx]]];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }

}



#pragma mark ----- Action
- (void)addPicAction{
    
    [self norSheetViewWithTitle:@""
                        mess:@""
                            theme:UIColor.blackColor
                            oneTitle:@"拍照".rh_localized
                               twoTitle:@"相册".rh_localized
                                       oneHandler:^{
        [self addPhotoFromCamera];
    }
                                       twoHandler:^{
        [self addPhotoFromAlbum:NO];
        
   }];
}

#pragma mark ----- 完成图片选择
-(void)finishPictureSelect:(UIImage *)image
{
    
    RHEditHeadCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    [cell setHeadImg:image];
    self.uploadImg = image;
    
}

//从相机拍照
- (void)addPhotoFromCamera{
    if (![ZLPhotoManager haveCameraAuthority]) {
        NSString *message = [NSString stringWithFormat:GetLocalLanguageTextValue(ZLPhotoBrowserNoCameraAuthorityText), kAPPName];
        [SVProgressHUD showInfoWithStatus:message];
        return;
    }
    
    ZLCustomCamera *camera = [[ZLCustomCamera alloc] init];
    camera.allowTakePhoto = YES;
    camera.allowRecordVideo = NO;
    
    kWeakSelf;
    camera.doneBlock = ^(UIImage *image, NSURL *videoUrl) {
        
        [weakSelf finishPictureSelect:image];
         
    };
    [self showDetailViewController:camera sender:nil];
}

//从相册选择图片
//hasCamera -- 是否附带拍照
- (void)addPhotoFromAlbum:(BOOL)hasCamera{
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
    //是否升序排列，预览界面不受该参数影响
    actionSheet.configuration.sortAscending = NO;
    //设置语言
    actionSheet.configuration.languageType = (ZLLanguageType)[[kUserDefaults objectForKey:@"ZLLanguage"]integerValue];
    //设置相册内部显示拍照按钮
    actionSheet.configuration.allowTakePhotoInLibrary = hasCamera?YES:NO;
    //设置在内部拍照按钮上实时显示相机俘获画面
    actionSheet.configuration.showCaptureImageOnTakePhotoBtn = hasCamera?YES:NO;
    //设置是否允许选择原图
    actionSheet.configuration.allowSelectOriginal = YES;
    //设置是否允许选择视频
    actionSheet.configuration.allowSelectVideo = NO;
    //设置是否允许选择gif
    actionSheet.configuration.allowSelectGif = NO;
    //是否显示选中图片的index 默认YES
    actionSheet.configuration.showSelectedIndex = NO;
    //是否允许编辑
    actionSheet.configuration.allowEditImage = NO;
    
    //预览选择模式下 拍照/相册/取消 的字体颜色 默认 blackColor
    actionSheet.configuration.previewTextColor = kCOLOR_HEX(@"#666666");
    //遮罩层颜色， 默认 blackColor alpha 0.2
    actionSheet.configuration.selectedMaskColor = [[UIColor blackColor] colorWithAlphaComponent: 0.7f];
    // 导航条颜色，默认 rgb(44, 45, 46)
    actionSheet.configuration.navBarColor = [UIColor whiteColor];
    // 导航标题颜色，默认 white
    actionSheet.configuration.navTitleColor = kCOLOR_HEX(@"#222222");
    // 底部工具栏按钮 可交互 状态标题颜色，默认 white
    actionSheet.configuration.bottomBtnsNormalTitleColor = kCOLOR_HEX(@"#222222");
    //底部工具栏按钮 可交互 状态背景颜色，默认rgb(80, 169, 56)
    actionSheet.configuration.bottomBtnsNormalBgColor = kCOLOR_HEX(@"#e9e9e9");
    //底部工具栏按钮 不可交互 状态背景颜色，默认rgb(39, 80, 32)
    //actionSheet.configuration.bottomBtnsDisableBgColor = CDisBtnColor;
    // 底部工具条底色，默认 rgb(44, 45, 46)
    actionSheet.configuration.bottomViewBgColor = kCOLOR_HEX(@"#ffffff");
    //设置照片 cell的圆角弧度
    actionSheet.configuration.cellCornerRadio = 5.0;
    //状态栏样式 默认 UIStatusBarStyleLightContent
    actionSheet.configuration.statusBarStyle = UIStatusBarStyleDefault;
    //设置照片最大预览数
    //actionSheet.configuration.maxPreviewCount = 2;
    //设置照片最大选择数
    actionSheet.configuration.maxSelectCount = 1;
    
    actionSheet.sender = self;

    [actionSheet showPhotoLibrary];
    
    kWeakSelf;
    [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
        
        UIImage *image = images[0];
        NSData *imageData = UIImageJPEGRepresentation(image, 1.0f);
        NSLog(@"--->图片大小: %ld k", (long)(imageData.length / 1024));
        
        [weakSelf finishPictureSelect:image];
        
    }];

    actionSheet.selectImageRequestErrorBlock = ^(NSArray<PHAsset *> * _Nonnull errorAssets, NSArray<NSNumber *> * _Nonnull errorIndex) {
    };
    
    actionSheet.cancleBlock = ^{
        
       
    };
}


//MARK: NOTE == 普通Sheet弹窗，按钮1和按钮2  主题色
- (void)norSheetViewWithTitle:(NSString *)title
                         mess:(NSString *)mess
                        theme:(UIColor *)themeColor
                     oneTitle:(NSString *)oneTitle
                     twoTitle:(NSString *)twoTitle
                   oneHandler:(dispatch_block_t)oneHandler
                   twoHandler:(dispatch_block_t)twoHandler{
    kWeakSelf;
    QMUIAlertAction *defaulAction = [QMUIAlertAction actionWithTitle:@"默认头像".rh_localized style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        [weakSelf finishPictureSelect:[UIImage imageNamed:@"kwt_avatar_default"]];
    }];
    
    // 底部按钮
    QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle: @"取消".rh_localized style:QMUIAlertActionStyleCancel handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        
    }];
    QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle: oneTitle style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        if (oneHandler) {
            oneHandler();
        }
    }];

    QMUIAlertAction *action3 = [QMUIAlertAction actionWithTitle: twoTitle style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        if (twoHandler) {
            twoHandler();
        }
    }];
    
    QMUIAlertController *alertController = [[QMUIAlertController alloc] initWithTitle: title message: mess preferredStyle:QMUIAlertControllerStyleActionSheet];
    /// sheet内容的圆角，默认值是 13，以保持与系统默认样式一致
    alertController.sheetContentCornerRadius = 6;
    /// sheet按钮高度，默认值是 57，以保持与系统默认样式一致
    alertController.sheetButtonHeight = 58;
    alertController.sheetContentMargin = UIEdgeInsetsMake(10, 12, 10, 12);
    /// sheet的最大宽度，默认值是5.5英寸的屏幕的宽度减去水平的 sheetContentMargin
    //alertController.sheetContentMaximumWidth = 320;
    
    NSMutableDictionary *titleAttributs = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetTitleAttributes];
    titleAttributs[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#222222");
    titleAttributs[NSFontAttributeName] = [UIFont systemFontOfSize:16];
    titleAttributs[NSParagraphStyleAttributeName] = [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight: 22 lineBreakMode: NSLineBreakByTruncatingTail textAlignment: NSTextAlignmentCenter];
    
    /// sheet标题样式，默认@{NSForegroundColorAttributeName:UIColorMake(143, 143, 143),NSFontAttributeName:UIFontBoldMake(13),NSParagraphStyleAttributeName:[NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:0 lineBreakMode:NSLineBreakByTruncatingTail]}
    alertController.sheetTitleAttributes = titleAttributs;
    
    NSMutableDictionary *messageAttributs = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetMessageAttributes];
     messageAttributs[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#444444");
       messageAttributs[NSFontAttributeName] = [UIFont systemFontOfSize:14];
       messageAttributs[NSParagraphStyleAttributeName] = [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight: 22 lineBreakMode: NSLineBreakByTruncatingTail];
    /// sheet信息样式，默认@{NSForegroundColorAttributeName:UIColorMake(143, 143, 143),NSFontAttributeName:UIFontMake(13),NSParagraphStyleAttributeName:[NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:0 lineBreakMode:NSLineBreakByTruncatingTail]}
    alertController.sheetMessageAttributes = messageAttributs;
    
    //alert头部（非按钮部分）背景色
    alertController.alertHeaderBackgroundColor = UIColorWhite;
    //alert按钮背景色
    alertController.alertButtonBackgroundColor = UIColorWhite;
    //alert上分隔线颜色
    alertController.alertSeparatorColor = kCOLOR_HEX(@"#f5f5f5");
    /// alert头部title和message之间的间距
    alertController.alertTitleMessageSpacing = 5;
    
    NSMutableDictionary *buttonAttributes = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetButtonAttributes];
    buttonAttributes[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#666666");
    buttonAttributes[NSFontAttributeName] = [UIFont systemFontOfSize:16];

    alertController.sheetButtonAttributes = buttonAttributes;
    
    NSMutableDictionary *cancelButtonAttributes = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetCancelButtonAttributes];
    cancelButtonAttributes[NSForegroundColorAttributeName] = themeColor;
    cancelButtonAttributes[NSFontAttributeName] = [UIFont systemFontOfSize:16];
    alertController.sheetCancelButtonAttributes = cancelButtonAttributes;
    
    [alertController addAction:defaulAction];
    [alertController addAction:action1];
    [alertController addAction:action2];
    [alertController addAction:action3];
    [alertController showWithAnimated:YES];
}



//压缩图片质量   maxLength  单位: kb
- (UIImage *)compressImageQuality:(UIImage *)image toByte:(NSInteger)maxLength {
    
     CGFloat compression = 1;
     NSData *data = UIImageJPEGRepresentation(image, compression);
     while (data.length / 1024 > maxLength && compression > 0) {
         compression -= 0.05;
         // When compression less than a value, this code dose not work
         data = UIImageJPEGRepresentation(image, compression);
         NSLog(@"====>压缩了一次后: %ld k",(long)(data.length / 1024));
     }
     UIImage *resultImage = [UIImage imageWithData:data];
     return resultImage;
}


#pragma mark --------点击确定 先图片上传 ----------------
-(void)uploadHeadImage
{
    if(self.uploadImg){
        [QMUITips showLoading:@"压缩图片...".rh_localized inView:self.view];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            UIImage *compressImg = [self compressImageQuality:self.uploadImg toByte:2000];
            dispatch_async(dispatch_get_main_queue(), ^{
                [QMUITips hideAllTipsInView:self.view];
                kWeakSelf;
                [QMUITips showLoading:@"上传图片...".rh_localized inView:self.view];
                [BaseModel startUploadWithCompletionAPIKey:H_uploadImage rgument:@{@"file":@"ios"} image:compressImg imageName:nil requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                    if(resultModel.code == 200){
                        [QMUITips showSucceed:@"上传成功".rh_localized inView:weakSelf.view];
                        //保存图片参数
                        [weakSelf.editInfoDic setObject:request.responseObject[@"url"] forKey:@"avatar"];
                        [weakSelf uploadAccountInfo];
                    }} requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                        
                        
                        
                    }];
            });
        });

    }else{
        //没有图像,个性个人信息
        [self uploadAccountInfo];
    }
    
    
}

#pragma mark ------- 修改个人信息 ---------
-(void)uploadAccountInfo
{
    NSLog(@"----个人信息参数:%@",self.editInfoDic);
    if(self.editInfoDic.allKeys.count>0){
        [QMUITips showLoading:@"修改个人信息...".rh_localized inView:self.view];
        [BaseModel startPutWithCompletionAPIKey:H_updateAccount argument:self.editInfoDic requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if(resultModel.code == 200){
                [QMUITips showSucceed:@"修改成功".rh_localized inView:self.view hideAfterDelay:1];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"AccountInfoUpdateNO" object:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                });
               
            }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                        
        }];
    }else{
        //没有信息提交,退出当前页
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark ----- 绑定用户 ----------
-(void)bindUser:(NSString *)content
{
    NSError *error;
    NSData *jsonData = [content dataUsingEncoding:NSUTF8StringEncoding];
     
    NSDictionary *dicInfo = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];

    if (![dicInfo isKindOfClass:[NSDictionary class]]){
        [QMUITips showError:@"数据错误".rh_localized];
        return;
    }
    
    if(![dicInfo[@"serverAdress"] isEqualToString:[NetworkConfig sharedConfig].baseUrl])
    {
        [QMUITips showError:@"只有同一区域的用户才能绑定".rh_localized];
        return;
    }
    [QMUITips showLoadingInView:self.view];
    [BaseModel startWithCompletionAPIKey:H_bindSuper argument:@{@"sendEmail":dicInfo[@"email"]} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            
            [QMUITips showSucceed:@"绑定用户成功".rh_localized inView:self.view hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                //绑定成功后获取一下个人信息,根据角色重新加载对应控制器
                [QMUITips showLoadingInView:self.view];
                [[PrivateMange share]getUserInfoSuccess:^(RHUserModel * _Nonnull userModel) {
                    [[NSNotificationCenter defaultCenter]postNotificationName:UserRoleDidChangeNotification object:nil];
                }];
            });
        }
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                
    }];
}

#pragma mark ------ 扫描二维码

- (void)scanQRC{
    if ([self isCameraAvailable]) {
        [self isCanVisitPhotoAndCameraAuthorization:^(BOOL isOK,NSString *alerStr) {
            if (isOK) {
                NSLog(@"权限OK");
                kWeakSelf;
                CDZQRScanViewController *controller = [[CDZQRScanViewController alloc] init];
                controller.resultCallBack = ^(NSString *email) {
                    [weakSelf bindUser:email];
                };
                 RHNavigationController *nav = [[RHNavigationController alloc] initWithRootViewController:controller];
                [nav setModalPresentationStyle:UIModalPresentationOverFullScreen];
                [self presentViewController:nav animated:YES completion:^{
                    
                }];
            }else{
                if (alerStr) {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:alerStr preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *conform = [UIAlertAction actionWithTitle:@"去设置".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                         if (@available(iOS 10.0, *)) {
                             [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
                             } else {
                             NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                             if ([[UIApplication sharedApplication] canOpenURL:url]) {
                                 [[UIApplication sharedApplication] openURL:url];
                             }
                         }
                    }];
                    
                    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        NSLog(@"点击了取消按钮");
                    }];
                    [alert addAction:cancel];
                    [alert addAction:conform];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }
        }];
    }else{
        NSLog(@"摄像头不可用");
    }

}

// 判断设备是否有摄像头
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}
- (void)isCanVisitPhotoAndCameraAuthorization:(void(^)(BOOL isOK,NSString *alerStr))result {
    PHAuthorizationStatus photo_status = [PHPhotoLibrary authorizationStatus];
    AVAuthorizationStatus camera_status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (photo_status == PHAuthorizationStatusAuthorized&&camera_status ==AVAuthorizationStatusAuthorized) {
        result(YES,nil);
        return;
    }
    
    if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied||
        camera_status ==AVAuthorizationStatusDenied || camera_status ==AVAuthorizationStatusRestricted) {
        if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied) {
            result(NO,@"Please allow access photos in iPhone's Settings");
        }else{
            result(NO,@"Please allow access camera in iPhone's Settings");
        }
        return ;
    }
    
    if (camera_status == AVAuthorizationStatusNotDetermined) {
        //点击弹框授权
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(!granted){//不允许
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"未开启相机权限,请到设置中开启");
                    result(NO,nil);
                });
            }else{
                if (photo_status == PHAuthorizationStatusNotDetermined) {
                    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                               // 回调是在子线程的
                               NSLog(@"%@",[NSThread currentThread]);
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   if (status != PHAuthorizationStatusAuthorized) {
                                         NSLog(@"未开启相册权限,请到设置中开启");
                                         result(NO,nil);
                                   }else{
                                         result(YES,nil);
                                   }
                               });
                     
                           }];
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        result(YES,nil);
                    });
                }

            }
        }];
        return;
    }
    
    if (photo_status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                   // 回调是在子线程的
                   NSLog(@"%@",[NSThread currentThread]);
                   dispatch_async(dispatch_get_main_queue(), ^{
                       if (status != PHAuthorizationStatusAuthorized) {
                             NSLog(@"未开启相册权限,请到设置中开启");
                             result(NO,nil);
                       }else{
                             result(YES,nil);
                       }
                   });
               }];
    }
}

@end
